package com.cn.chaomeng.controller;

import com.alibaba.fastjson.JSONArray;
import com.cn.chaomeng.constant.SysParam;
import com.cn.chaomeng.dto.ResultDTO;
import com.cn.chaomeng.model.Orderfo;
import com.cn.chaomeng.model.Orders;
import com.cn.chaomeng.service.ExChangeService;
import com.cn.chaomeng.utils.DateUtil;
import com.cn.chaomeng.vo.app.Data;
import com.cn.chaomeng.vo.app.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 范中燊
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: TODO
 * @date ${date} ${time}
 */
@Controller
@RequestMapping("app")
public class AppController
{
    @Autowired
    private ExChangeService exChangeService;

    @RequestMapping("/main")
    public ModelAndView login(HttpServletRequest request)
        throws Exception
    {
        return new ModelAndView("app/redirect");
    }

    /**
     * 生成订单
     *
     * @param vo
     * @return
     */
    @RequestMapping("/generating_order")
    @ResponseBody
    public ResultDTO generatingOrder(@RequestBody OrderVO vo)
    {

        ResultDTO resultDTO = new ResultDTO();

        Map<String, Object> selectMap = new HashMap<String, Object>();

        Orders orders = new Orders();
        orders.setOpenid(vo.getOpenId());
        orders.setTotalcount(vo.getTotalcount());
        orders.setTotalprices(vo.getTotalprices());
        orders.setState(SysParam.NO_PAY_STATE);
        orders.setCreateTime(DateUtil.getTimestamp() + "");

        exChangeService.saveOrders(orders);

        List<Data> dataList = JSONArray.parseArray(vo.getData(), Data.class);
        for (Data data : dataList)
        {
            Orderfo orderfo = new Orderfo();
            orderfo.setOrderid(orders.getOrderid());
            orderfo.setCreateTime(DateUtil.getTimestamp() + "");
            orderfo.setFid(data.getFid());
            orderfo.setNumber(data.getNum());
            exChangeService.saveOrderfo(orderfo);
        }

        resultDTO.setResult(true);
        resultDTO.setCode(200);
        resultDTO.setData(orders);
        return resultDTO;
    }

}
